package com.msh.automatic.android.api.util;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.msh.automatic.android.api.entity.Device;
import com.nimbusds.jwt.SignedJWT;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.time.Duration;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import java.util.UUID;

@Component
public class DeviceActivationInfoUtil {

    public static final ThreadLocal<SignedJWT> sessionLocal = new ThreadLocal<>();

    public static void set(SignedJWT jwt){
        sessionLocal.set(jwt);
    }
    public static SignedJWT get(){
        return sessionLocal.get();
    }
    public static void remove(){
        sessionLocal.remove();
    }

    public static Boolean isActivation(Device device){
        if(!device.getOnline()){
            device.setActivation(false);
            device.setMessage("mqtt不在线");
        }else if (DateUtil.between(device.getHeartbeat(), new Date(), DateUnit.MINUTE) > 2){
            device.setActivation(false);
            device.setMessage("心跳时间超过2分钟");
        }else if (StrUtil.isEmpty(device.getActivationCode())){
            device.setActivation(false);
            device.setMessage("未激活：激活码为空");
        }else if (!com.msh.automatic.android.api.util.DateUtil.isDateTodayOrAfter(device.getExpirationTime())){
            device.setActivation(false);
            device.setMessage("未激活：已过期");
        }else if (!device.getAccessibility()){
            device.setActivation(false);
            device.setMessage("未开启无障碍服务");
        }else if (!device.getPower()){
            device.setActivation(false);
            device.setMessage("未加入电源白名单");
        }else if (!device.getFileManager()){
            device.setActivation(false);
            device.setMessage("未授权文件管理");
        }else if (!device.getInstallApk()){
            device.setActivation(false);
            device.setMessage("未授权安装app");
        }else{
            device.setActivation(true);
            device.setMessage("");
        }
        return device.getActivation();
    }
    public static String getDeviceId(){
        if(sessionLocal.get()==null){
            return "";
        }
        try {
            return sessionLocal.get().getJWTClaimsSet().getSubject();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
